#include "common.h"

struct state_report  state_report_data;
struct operate_state operate_parm;

struct ada_parm adaptor_parm;
void (*go_main_program)(void) = NULL;

void delay_time(unsigned int times)
{
    while (times--)
        ;
}

void memory_set(void *dst, unsigned char data, unsigned int size)
{
    unsigned char *cursor = (unsigned char *)dst;
    int            i      = 0;
    for (i = 0; i < size; i++) {
        (*cursor) = data;
        cursor++;
    }
}

void memory_copy(void *dst, void *src, unsigned int len)
{
    unsigned char *d = dst;
    unsigned char *s = src;
    for (unsigned int i = 0; i < len; i++) {
        *d = *s;
        d++;
        s++;
    }
}

void init_main_var(void)
{
    go_main_program = *((volatile unsigned int *)(PROGRAM_OFFSET + 4));
}

void init_var(void)
{
    init_main_var();
}

void delay_ms(unsigned int times)
{
    unsigned long count = 0;
    unsigned int  i     = 0;
    while (times--) {
        i = 12000;
        while (i--)
            ;
    }
}

unsigned char test[] = {12, 23, 21};

void (*test_fun)(void) = NULL;

void reset_apb(void)
{
    rcc_reg->APB1RSTR = 0xffffffff;
    rcc_reg->APB2RSTR = 0xffffffff;
    delay_ms(10);
    rcc_reg->APB1RSTR = 0;
    rcc_reg->APB2RSTR = 0;
    nvic_reg->ICER[1] = (1 << 5);
    nvic_reg->ICER[1] = (1 << 22);
}

__asm void MSR_MSP(unsigned int addr)
{
    MSR          MSP, r0  // set Main Stack value
                 BX r14
}

int main(void)
{

    init_flash();
    init_rcc();
    init_gpio();
    init_var();

#if (BOOT_FOR_UART1)
    init_usart1();
#elif (BOOT_FOR_UART4)
    init_uart4();
#endif
    // init_general_timer4();
    init_timer6();
    // init_iwdg();
    // delay_ms(10000);

    set_time_delay(&timer6_count.handshake_wait, 5000);

    while (1) {
        if (judge_time_delay(&timer6_count.handshake_wait)) {
            clear_time_count(&timer6_count.handshake_wait);
            if (0 == update_ph) {

                reset_apb();
                __asm volatile("CPSID I");
                MSR_MSP(PROGRAM_OFFSET);
                go_main_program();
            }
        }

        usart_rx_process();
        request_data_process();
    }
}
